
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys
import os
from pathlib import Path

# 添加项目路径到Python路径
project_path = Path(__file__).parent
sys.path.insert(0, str(project_path))

from app import create_app

class ImageGenAPIService(win32serviceutil.ServiceFramework):
    _svc_name_ = "ImageGenAPI"
    _svc_display_name_ = "图生图转接API服务"
    _svc_description_ = "基于Gemini 2.0 Flash的图片生成和编辑API服务"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STARTED,
                            (self._svc_name_, ''))
        self.main()

    def main(self):
        try:
            # 切换到项目目录
            os.chdir(str(project_path))
            
            # 创建Flask应用
            app = create_app()
            
            # 启动服务
            app.run(host='0.0.0.0', port=5000, debug=False)
            
        except Exception as e:
            servicemanager.LogErrorMsg(f"服务启动失败: {e}")

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(ImageGenAPIService)
